package oakclub.global;

import com.google.gson.*;
import oakclub.entity.ResponseEntity;

import java.lang.reflect.Type;
import java.util.Date;

public class Json
{
    private static Gson parser;

    static
    {
        JsonSerializer<Date> dateSerializer = new JsonSerializer<Date>()
        {
            @Override
            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context)
            {
                return src == null ? new JsonPrimitive("") : new JsonPrimitive(DateFormatter.getFormatter("MM/dd/yyyy HH:mm:ss").format(src));
            }
        };

        JsonSerializer<java.sql.Date> sqlDateSerializer = new JsonSerializer<java.sql.Date>()
        {
            @Override
            public JsonElement serialize(java.sql.Date src, Type typeOfSrc, JsonSerializationContext context)
            {
                return src == null ? new JsonPrimitive("") : new JsonPrimitive(DateFormatter.getFormatter("MM/dd/yyyy").format(src));
            }
        };

        JsonSerializer<java.sql.Timestamp> sqlTimestampSerializer = new JsonSerializer<java.sql.Timestamp>()
        {
            @Override
            public JsonElement serialize(java.sql.Timestamp src, Type typeOfSrc, JsonSerializationContext context)
            {
                return src == null ? new JsonPrimitive("") : new JsonPrimitive(DateFormatter.getFormatter("MM/dd/yyyy HH:mm:ss").format(src));
            }
        };

        JsonSerializer<ResponseEntity.ErrorCode> errorCodeSerializer = new JsonSerializer<ResponseEntity.ErrorCode>()
        {
            @Override
            public JsonElement serialize(ResponseEntity.ErrorCode src, Type typeOfSrc, JsonSerializationContext context)
            {
                return src == null ? new JsonPrimitive("") : new JsonPrimitive(src.val());
            }
        };

        parser = new GsonBuilder()
            .serializeNulls()
            .registerTypeAdapter(Date.class, dateSerializer)
            .registerTypeAdapter(java.sql.Date.class, sqlDateSerializer)
            .registerTypeAdapter(java.sql.Timestamp.class, sqlTimestampSerializer)
            .registerTypeAdapter(ResponseEntity.ErrorCode.class, errorCodeSerializer)
            .create();
    }

    public static Gson getParser()
    {
        return parser;
    }
}
